package com.xiyoo.cw.service.impl;

import cn.hutool.core.text.CharSequenceUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xiyoo.cw.common.Result;
import com.xiyoo.cw.common.enums.ResultCode;
import com.xiyoo.cw.domain.CheckinRecords;
import com.xiyoo.cw.domain.TaskCountVO;
import com.xiyoo.cw.domain.UserTaskDetailVO;
import com.xiyoo.cw.domain.task.CheckinRequest;
import com.xiyoo.cw.domain.task.TaskRequest;
import com.xiyoo.cw.mapper.TaskMapper;
import com.xiyoo.cw.service.TaskService;
import com.xiyoo.cw.utils.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.util.*;

/**
 * @Description
 * @Author zhouzhongqing
 * @Date 2025/5/13 15:00
 * @Version 1.0
 **/
@Slf4j
@Service
public class TaskServiceImpl implements TaskService {

    @Resource
    private TaskMapper taskMapper;

    @Override
    public Result<Object> checkin(CheckinRequest request) {
        log.info("打卡开始，params={}", JSON.toJSONString(request));
        try {
            String email = SecurityUtils.getUserEmail();
            if (CharSequenceUtil.isBlank(email)) {
                log.info("打卡异常，email获取失败");
                return new Result<>(ResultCode.SERVER_ERROR);
            }
            LambdaQueryWrapper<CheckinRecords> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(CheckinRecords::getEmail, email)
                    .eq(CheckinRecords::getTaskId, request.getTaskId())
                    .apply("DATE(checkin_time) = {0}", LocalDate.now());
            CheckinRecords selectOne = taskMapper.selectOne(queryWrapper);
            if (Objects.nonNull(selectOne)) {
                log.info("该任务今天已经打过卡了，email={}, taskId={}", email, request.getTaskId());
                return new Result<>(ResultCode.CHECKIN_ERROR);
            }
            CheckinRecords build = CheckinRecords.builder()
                    .email(email)
                    .taskId(request.getTaskId())
                    .checkinTime(new Date())
                    .carbonReduction(request.getCarbonReduction())
                    .score(1)
                    .taskName(request.getTaskName())
                    .build();
            int rows = taskMapper.insert(build);
            log.info("打卡成功，email={},taskId={}，rows={}", email, request.getTaskId(), rows);
            return new Result<>(ResultCode.SUCCESS);
        } catch (Exception e) {
            log.error("打卡异常，email={},taskId={}", SecurityUtils.getUserEmail(), request.getTaskId(), e);
            return new Result<>(ResultCode.SERVER_ERROR);
        }
    }

    @Override
    public Result<Object> taskStatus(TaskRequest request) {
        log.info("任务状态查询，params={}", JSON.toJSONString(request));
        try {
            String email = SecurityUtils.getUserEmail();
            if (CharSequenceUtil.isBlank(email)) {
                log.info("任务状态查询异常，email获取失败");
                return new Result<>(ResultCode.SERVER_ERROR);
            }
            LambdaQueryWrapper<CheckinRecords> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(CheckinRecords::getEmail, email)
                    .eq(CheckinRecords::getTaskId, request.getTaskId())
                    .apply("DATE(checkin_time) = {0}", LocalDate.now());
            CheckinRecords selectOne = taskMapper.selectOne(queryWrapper);
            if (Objects.nonNull(selectOne)) {
                log.info("该任务状态已打卡，email={}, taskId={}", email, request.getTaskId());
                return new Result<>(ResultCode.SUCCESS, true);
            }
            return new Result<>(ResultCode.SUCCESS, false);
        } catch (Exception e) {
            log.error("任务状态查询异常，email={},taskId={}", SecurityUtils.getUserEmail(), request.getTaskId(), e);
            return new Result<>(ResultCode.SERVER_ERROR);
        }
    }

    @Override
    public Result<Object> details() {
        log.info("查询用户战绩详情。。。");
        try {
            String email = SecurityUtils.getUserEmail();
            if (CharSequenceUtil.isBlank(email)) {
                log.info("查询用户战绩详情异常，email获取失败");
                return new Result<>(ResultCode.SERVER_ERROR);
            }

            // 查询用户战绩 累计分数、减碳量
            UserTaskDetailVO detail = taskMapper.selectUserTaskDetail(email);
            if (Objects.isNull(detail)) {
                log.info("查询用户战绩详情失败");
                return new Result<>(ResultCode.ERROR);
            }

            log.info("查询用户战绩详情，result={}", JSON.toJSONString(detail));
            return new Result<>(ResultCode.SUCCESS, detail);
        } catch (Exception e) {
            log.error("查询用户战绩详情异常，email={}", SecurityUtils.getUserEmail(), e);
            return new Result<>(ResultCode.SERVER_ERROR);
        }
    }

    @Override
    public Result<Object> taskCount() {
        log.info("查询各任务总积分。。。");
        try {
            String email = SecurityUtils.getUserEmail();
            if (CharSequenceUtil.isBlank(email)) {
                log.info("查询各任务总积分，email获取失败");
                return new Result<>(ResultCode.SERVER_ERROR);
            }
            Set<Long> taskIdsWithCheckin = new HashSet<>();
            for (int i = 1; i <= 8; i++) {
                taskIdsWithCheckin.add(Long.parseLong(String.valueOf(i)));
            }

            // 查询用户战绩 累计分数、减碳量
            List<TaskCountVO> taskCountVOS = taskMapper.selectUserTaskCount(email);
            if (Objects.isNull(taskCountVOS)) {
                List<TaskCountVO> result = new ArrayList<>();
                for (int i = 1; i <= 8; i++) {
                    TaskCountVO taskCountVO = new TaskCountVO();
                    taskCountVO.setTaskId(Long.parseLong(String.valueOf(i)));
                    taskCountVO.setCount(0);
                    result.add(taskCountVO);
                }
                log.info("查询各任务总积分数据空");
                return new Result<>(ResultCode.SUCCESS, result);
            }

            // 填充未打卡的任务
            for (long taskId : taskIdsWithCheckin) {
                // 检查 taskId 是否在现有的 objects 中
                boolean isTaskCheckedIn = false;
                for (TaskCountVO taskCount : taskCountVOS) {
                    if (taskCount.getTaskId().equals(taskId)) {
                        isTaskCheckedIn = true;
                        break;
                    }
                }

                // 如果没有打卡记录，添加打卡次数为 0
                if (!isTaskCheckedIn) {
                    TaskCountVO taskCountVO = new TaskCountVO();
                    taskCountVO.setTaskId(taskId);
                    taskCountVO.setCount(0);  // 未打卡任务，次数为 0
                    taskCountVOS.add(taskCountVO);
                }
            }

            log.info("查询各任务总积分，result={}", JSON.toJSONString(taskCountVOS));
            return new Result<>(ResultCode.SUCCESS, taskCountVOS);
        } catch (Exception e) {
            log.error("查询各任务总积分异常，email={}", SecurityUtils.getUserEmail(), e);
            return new Result<>(ResultCode.SERVER_ERROR);
        }
    }
}
